#!/usr/bin/env python
#
# Copyright (C) 2010 Zajcev Evgeny <zevlg@yandex.ru>
#
# Version: 0.1
# X-URL: http://fprog.ru/contests/2009/geo/
#
## Commentary:
#
# usage: ./osmt.py [-vc] <osm-in> <poly> <osm-out>
#        -v      Be verbose
#        -c      completeObjects
#
## Code:


from __future__ import with_statement
import sys
import getopt
from itertools import takewhile, islice
from osmtrunc import Polygon, Osmtrunc, __version__, __author__

def make_polygon(polyfile):
    """Parse polygon file in Osmosis/Polygon_Filter_File_Format.
    Return a Polygon suitable for ``is_inside``."""
    def contours(f):
        def notEND(): return takewhile(lambda x: x[:3] != "END", f)
        def contour(): return [map(float, l.split()) for l in notEND()]
        return [(contour(), l[0] == "!") for l in notEND()]

    with open(polyfile) as f:
        # NOTE: use nice ``islice`` to skip first line, where filename is
        poly = Polygon()
        map(poly.add_contour, contours(islice(f, 1, None)))
        return poly.optimize()

def usage():
    print "Osmtrunc v%s by %s"%(__version__,__author__)
    print "usage: %s [-vc] <osm-in> <poly> <osm-out>"%sys.argv[0]
    print "\t-v\tBe verbose"
    print "\t-c\tcompleteObjects"
    sys.exit(0)

def osmtruncate((oi, pf, oo), opts=[]):
    """Truncate input ``.osm`` file OI using ``.poly`` file PF.
    Write output to OO file.
    All the work is actually done by ``Osmtrunc``"""
    if oo == "-" and '-v' in opts:
        # Can't be verbose if writing to stdout
        opts.remove('-v')

    otspoly = make_polygon(pf)
    ot = Osmtrunc(oi, oo, otspoly, opts)
    ot.process()

    if '-v' in opts:
        print "Statistics:"
        print "%d nodes (%d + %d), %d ways and %d relations saved"% \
              (ot.stats["nodes"] + ot.stats["cnodes"], \
               ot.stats["nodes"], ot.stats["cnodes"], \
               ot.stats["ways"], ot.stats["relations"])
        print "Processed in %f seconds"%ot.stats["run-time"]
        if any(map(lambda x: len(x)>0, ot.stats["dups"])):
            print "Duplicates found: %d nodes, %d ways, %d relations"% \
                  tuple(map(len, ot.stats["dups"]))

        sgrh, swnh = otspoly.ghits, otspoly.wnhits
        gperc = (100*sgrh)/(sgrh + swnh + 1)
        print "Node hits: %d by grid, %d by wn = %d%%"%(sgrh, swnh, gperc)

if __name__=="__main__":
    try:
        opts, sargs = getopt.getopt(sys.argv[1:], "vc")
    except getopt.GetoptError, err:
        print str(err)
        usage()
    if len(sargs) != 3: usage()

    osmtruncate(sargs, [a for (a,_) in opts])
